package com.yphone.ui.main;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.support.design.widget.TabLayout.Tab;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.yphone.net.HttpConstants;
import com.yphone.net.bean.BaseResultWrapper;
import com.yphone.net.helper.ActivityHttpHelper;
import com.yphone.tools.Constants;
import com.yphone.tools.MyLog;
import com.yphone.tools.ToastUtil;
import com.yphone.ui.dialog.CommSmallLoadingDialog;
import com.yphone.ui.event.MyEvent;
import com.yphone.ui.login.manager.LoginManager;
import com.yphone.ui.login.respone.UserInfo;
import com.yphone.ui.ysj.bean.RemoteConnectBean;
import com.yphone.utils.NetworkUtils;
import com.yphone.utils.RegexUtils;
import com.yphone.utils.ToastUtils;
import com.yw.game.floatmenu.FloatItem;
import com.yw.game.floatmenu.FloatLogoMenu;
import com.yw.game.floatmenu.FloatMenuView;
import com.zzkj.yunphone.R;
import com.iiordanov.bVNC.event.bVNCEvent;
import com.yphone.ui.yun.RemoteDeviceListActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class MainActivity extends FragmentActivity implements MainActivityContract.IView {

    private TabLayout tablayout;
    private FrameLayout mFrameLayout;
    private MainActivityContract.IPrestenter iPrestenter;

    public int tableat = 0;
    public Handler handler = new Handler();
    private View layout_edit_device_name;
    private EditText pop_edit_alter_dis_order;
    private RemoteConnectBean bean;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        initview();
        initData();
        initListener();
    }

    public void test(View v){
        CommSmallLoadingDialog.showDialog(this,"请稍等...");
    }


    private void initview() {
        this.tablayout = (TabLayout) findViewById(R.id.tablayout);
        this.mFrameLayout = (FrameLayout) findViewById(R.id.main_fram_layout);
        layout_edit_device_name = findViewById(R.id.layout_edit_device_name);
        layout_edit_device_name.setVisibility(View.GONE);
        layout_edit_device_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layout_edit_device_name.setVisibility(View.GONE);
            }
        });
        pop_edit_alter_dis_order = findViewById(R.id.pop_edit_alter_dis_order);
        findViewById(R.id.pop_ok_alter_dis_order).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!NetworkUtils.isConnected()) {
                    ToastUtils.showLong((CharSequence) "保存失败，请检查网络后重试");
                } else if ("".equals(pop_edit_alter_dis_order.getText().toString().trim())) {

//                    EventBus.getDefault().post(new MyEvent.NotifyDeviceNameEdit(pop_edit_alter_dis_order.getText().toString().trim(),bean));
                    layout_edit_device_name.setVisibility(View.GONE);
                } else if (!RegexUtils.isMatch(Constants.NICK_MATCHING, pop_edit_alter_dis_order.getText().toString().trim())) {
                    ToastUtils.showLong((CharSequence) MainActivity.this.getString(R.string.alter_dis));
                } else {
                    String remake = pop_edit_alter_dis_order.getText().toString().trim();
                    iPrestenter.updateDeviceRemake(bean.id+"", remake);
                    EventBus.getDefault().post(new MyEvent.NotifyDeviceNameEdit(remake, bean));
                    layout_edit_device_name.setVisibility(View.GONE);
                }

            }
        });
    }

    private void initData() {
        setPresenter((MainActivityContract.IPrestenter) new MainActivityPresenter(this));
        Tab tab_item_ysj = this.tablayout.newTab();
        tab_item_ysj.setCustomView((int) R.layout.tab_item_ysj_layout);
//        TabLayout.Tab tab_item_extend = this.tablayout.newTab();
//        tab_item_extend.setCustomView((int) R.layout.tab_item_extend_layout);
//        Tab tab_item_manager = this.tablayout.newTab();
//        tab_item_manager.setCustomView((int) R.layout.tab_item_manage_layout);
        Tab tab_item_my = this.tablayout.newTab();
        tab_item_my.setCustomView((int) R.layout.tab_item_my_layout);
//        this.mViewHotDot = tab_item_my.getCustomView().findViewById(R.id.tab_item_my_layout_img_hot_dot);
        this.tablayout.addTab(tab_item_ysj, false);
//        this.tablayout.addTab(tab_item_extend);
//        this.tablayout.addTab(tab_item_manager);
        this.tablayout.addTab(tab_item_my, false);
        tablayout.getTabAt(0).select();
        this.iPrestenter.start();
        tablayout.setBackgroundColor(Color.parseColor("#222D4E"));


//        this.iPrestenter.isShowRedDot(this.mViewHotDot);
        if (LoginManager.getInstance().isLogin()) {
            iPrestenter.requestInit();
        }
    }

    private void initListener() {
        this.tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            public void onTabSelected(Tab tab) {
                MainActivity.this.tableat = tab.getPosition();
                MainActivity.this.iPrestenter.onTabSelected(tab.getPosition());
                if (tab.getPosition() == 0) {
                    tablayout.setBackgroundColor(Color.parseColor("#222D4E"));
                } else {
                    tablayout.setBackgroundColor(Color.WHITE);
                }
            }

            public void onTabUnselected(Tab tab) {
                MainActivity.this.iPrestenter.onTabUnselected(tab.getPosition());
            }

            public void onTabReselected(Tab tab) {
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public FragmentActivity getCurrentActivity() {
        return this;
    }

    @Override
    public Context getCurrentContext() {
        return this;
    }

    @Override
    public void showToast(String str) {
        Toast.makeText(getCurrentContext(), str, Toast.LENGTH_LONG).show();
    }

    @Override
    public void setPresenter(MainActivityContract.IPrestenter iPrestenter) {
        this.iPrestenter = iPrestenter;

    }

    @Subscribe
    public void onEventMainThread(final bVNCEvent.ShowDevicesListEvent event) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(MainActivity.this, RemoteDeviceListActivity.class);
                intent.putExtra("id", event.id);
                startActivity(intent);
            }
        });
    }

    @Subscribe
    public void onEventMainThread1(final MyEvent.ShowDeviceNameEdit event) {
        layout_edit_device_name.setVisibility(View.VISIBLE);
        this.bean = event.bean;
    }

    @Subscribe
    public void onEventMainThread(final MyEvent.LoginSuccessEvent event) {
        EventBus.getDefault().post(new bVNCEvent.UInotifyEvent());

//        iPrestenter.requestInit();
    }

    @Subscribe
    public void onEventMainThread(final MyEvent.updateInit event) {
        if (LoginManager.getInstance().isLogin()) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    CommSmallLoadingDialog.showDialog(MainActivity.this, "加载设备，请稍等...");
                    iPrestenter.requestInit();
                }
            },500);


        }
    }

    @Subscribe
    public void onEventMainThread(final MyEvent.paySuccess event) {
        if (LoginManager.getInstance().isLogin()) {
            CommSmallLoadingDialog.showDialog(MainActivity.this, "");
            iPrestenter.requestInit();
        }
        ToastUtil.showToast("支付成功！");
    }

    @Subscribe
    public void onEventMainThread(final bVNCEvent.upDeviceImg event) {
        MyLog.e("上传img id = " + event.id + "   --end--");

        ActivityHttpHelper<BaseResultWrapper<Object>> helper = new ActivityHttpHelper<>(new TypeToken<BaseResultWrapper<Object>>() {
        });
        HashMap<String, String> map = new HashMap<>();
        map.put("token", LoginManager.getInstance().getToken());
        map.put("d_token", event.d_token);
        map.put("view", event.img);

        UserInfo info = LoginManager.getInstance().getInfo();
        List<RemoteConnectBean> remoteConnectBeans = info.remoteConnectBeans;
        for (int i = 0; i < remoteConnectBeans.size(); i++) {
            RemoteConnectBean bean = remoteConnectBeans.get(i);
            if (bean.id == event.id) {
                bean.view = event.img;
                break;
            }
        }

        helper.sendPostRequest(HttpConstants.saveDeviceView, map, HttpConstants.TIME_OUT3);
        LoginManager.getInstance().saveInfo(info);
        EventBus.getDefault().post(new bVNCEvent.UInotifyEvent());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
